package com.loveazure.bll;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.loveazure.eo.Course;
import com.loveazure.eo.Dict;
import com.loveazure.eo.User;
import com.loveazure.eo.UserCourse;
import com.loveazure.eo.WordLearned;
import com.loveazure.ui.MainFrame.Status;
import com.loveazure.util.HibernateUtil;
import com.loveazure.util.MyLogger;
import com.loveazure.util.FileUtil;
import com.loveazure.util.WebDict;

public class Operation {

	private SessionFactory factory;
	private Logger logger;
	private Session session;

	public Operation() {
		this.factory = HibernateUtil.getSessionFactory();
		this.session = factory.openSession();
		logger = MyLogger.getLogger();
	}

	public boolean addUser(User user) {
		if (user == null || user.getName() == null || "".equals(user.getName())) {
			logger.info("user info is incorrect!");
			return false;
		}
		try {

			session.beginTransaction();
			List<Object> list = session.createQuery(
					"from User where name='" + user.getName() + "'").list();
			if (list.size() > 0) {
				logger.info("user:" + user.getName() + " is already exist!");
				return false;
			}
			user.setLoginDate(new Date());
			session.save(user);
			session.getTransaction().commit();

		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return true;
	}

	public boolean deleteUser(User user) {
		if (user == null || user.getId() == 0) {
			logger.info("user info is incorrect");
			return false;
		}
		if ("default".equals(user.getName())) {
			logger.info("user default can not be deleted!");
			return false;
		}
		try {
			session.beginTransaction();
			session.delete(user);
			session.getTransaction().commit();
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
	}

	public void login(User user) {
		Handler handler = Handler.getInstance();
		handler.setUser(user);
		session.beginTransaction();
		user.setLoginDate(new Date());
		session.update(user);
		session.getTransaction().commit();
		handler.getFrame().switchPanel(Status.CONFIG);
	}

	public User[] getAllUsers() {
		session.beginTransaction();

		List<Object> list = session.createQuery("from User").list();
		User[] users = new User[list.size()];
		for (int i = 0; i < list.size(); i++) {
			users[i] = (User) list.get(i);
		}
		session.getTransaction().commit();
		return users;
	}

	public void updateLearnedWord(WordLearned wordlearned) {
		session.beginTransaction();
		if (wordlearned.getId() == 0) {
			Set<WordLearned> set = Handler.getInstance().getUserCourse()
					.getWordLearned();
			set.add(wordlearned);
			session.update(wordlearned.getUserCourse());
			System.out.println("aaa");
		} else {
			
			session.update(wordlearned);
		}

		session.getTransaction().commit();
	}

	public UserCourse[] getAvailableCourse() {
		User user = Handler.getInstance().getUser();
		if (user != null) {

			return user.getUserCourse().toArray(new UserCourse[0]);
		} else {
			return null;
		}
	}

	public Course processImportFile(File file, String courseName) {

		if (file == null) {
			return null;
		}
		String fileName = file.getName();

		Course course = new Course();
		course.setCourseName(courseName);
		course.setFileName(fileName);

		try {
			session.beginTransaction();
			session.save(course);
			session.getTransaction().commit();
			return course;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	public Course[] getAllCourse() {
		try {
			session.beginTransaction();
			List<Object> list = session.createQuery("from Course").list();
			session.getTransaction().commit();
			return list.toArray(new Course[0]);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	public boolean registerCourse(Course course) {

		User user = Handler.getInstance().getUser();
		if (user == null) {
			logger.info("user can not be null");
			return false;
		}
		for (UserCourse uc : user.getUserCourse()) {
			if (uc.getCourse().getId() == course.getId()) {
				logger.info("The selected course has already registered");
				return false;
			}
		}
		File source = new File("words" + File.separatorChar
				+ course.getFileName());
		if (!source.exists()) {
			logger
					.error("course file [" + source.getPath()
							+ "] is not exist!");
			return false;
		}
		File target = new File("user" + File.separatorChar + user.getName());
		target.mkdirs();
		target = new File(target, course.getFileName());
		FileUtil.copyFile(source, target);

		try {
			session.beginTransaction();

			UserCourse userCourse = new UserCourse();
			userCourse.setCourse(course);
			userCourse.setUser(user);

			user.getUserCourse().add(userCourse);
			session.save(user);

			session.getTransaction().commit();
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage());
			session.getTransaction().rollback();
			return false;
		}
	}

	public WordLearned insertNewLearnedWord(String word) {
		try {
			session.beginTransaction();
			WordLearned wordLearned = new WordLearned();
			List list = session.createQuery(
					"from Dict where name='" + word + "'").list();
			if (list == null || list.size() == 0) {
				return null;
			}
			wordLearned.setTimes(1);
			wordLearned.setDict((Dict) list.get(0));
			wordLearned.setUserCourse(Handler.getInstance().getUserCourse());

			session.save(wordLearned);
			session.getTransaction().commit();
			return wordLearned;

		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

	public Dict getDictByWord(String word) {
		Dict dict;
		try {
			session.beginTransaction();

			List list = session.createQuery(
					"from Dict where name='" + word + "'").list();

			if (list != null && list.size() != 0) {
				dict = (Dict) list.get(0);
			} else {
				dict = WebDict.getDict(word);
				if (dict == null) {
					dict = null;
				}
				session.save(dict);
			}
			session.getTransaction().commit();
			return dict;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void deleteUserCourse(UserCourse row) {
		session.beginTransaction();
		try {
			User user = Handler.getInstance().getUser();
			user.getUserCourse().remove(row);
			row.setUser(null);
			session.save(user);
			String filePath = "user" + File.separatorChar + user.getName()
					+ File.separatorChar + row.getCourse().getFileName();
			File file = new File(filePath);
			file.delete();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}

	}

	public void deleteCourse(Course row) {
		session.beginTransaction();
		try {
			session.delete(row);
			String filePath = "words" + File.separatorChar + row.getFileName();
			File file = new File(filePath);
			file.delete();
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}

	}

}
